const WebSocket = require('ws');
const http = require('http')
// 创建websocket实例
const wss = new WebSocket.Server({ port: 8888 });
// 监听ws链接是否打开 
wss.on('connection', function (ws) {
    // 监听客户端消息
    ws.on('message', function (message) {
        const msg = message.toString()
        // console.log(message.toString(), '客户端来消息了');
        http.get(`http://api.qingyunke.com/api.php?key=free&appid=0&msg=${msg}`, (response) => {
            let data = ''
            response.on('data', (chunk) => {
                data += chunk;
            })
            response.on('end', () => {
                const res = JSON.parse(data)
                console.log(res.content, 'res');
                // 将响应消息发送给客户端浏览器
                ws.send(res.content)
            })
        })
    });
    // 监听通信通道的关闭
    ws.on('close', (e) => {
        console.log(e, 'close');
    })
    // 向客户端发送消息
    // ws.send('something');
});